/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.estoque.Telas;

import br.com.estoque.Clientes.Cliente;
import br.com.estoque.Clientes.ClienteDAO;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author note
 */
public class Clientes extends javax.swing.JFrame {

    /**
     * Creates new form Clientess
     */
    public Clientes() {
        initComponents();
        desabilitarCampos();
    }

  //  ClienteTableModel tmClientes = new ClienteTableModel();
     DefaultTableModel tmClientes = new DefaultTableModel(null, new String[]{"Código", "Nome", "CPF", "Telefone"});
     List<Cliente> clientes;
     ListSelectionModel lsmClientes;
     String tipoCadastro;
     
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tfClientes = new javax.swing.JTextField();
        botaoPesquisarCliente = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbClientes = new javax.swing.JTable();
        labelNome = new javax.swing.JLabel();
        tfNomeClientes = new javax.swing.JTextField();
        labelEndereco = new javax.swing.JLabel();
        tfEndereco = new javax.swing.JTextField();
        labelBairro = new javax.swing.JLabel();
        tfBairro = new javax.swing.JTextField();
        labelCidade = new javax.swing.JLabel();
        tfCidade = new javax.swing.JTextField();
        labelUF = new javax.swing.JLabel();
        tfUF = new javax.swing.JTextField();
        labelCEP = new javax.swing.JLabel();
        labelTelefoneClientes = new javax.swing.JLabel();
        botaoNovoCliente = new javax.swing.JButton();
        botaoSalvarCliente = new javax.swing.JButton();
        botaoAlterarCliente = new javax.swing.JButton();
        botaoCancelarCliente = new javax.swing.JButton();
        botaoFecharCliente = new javax.swing.JButton();
        labelAviso = new javax.swing.JLabel();
        labelCPFCNPJ = new javax.swing.JLabel();
        tfCPF = new javax.swing.JFormattedTextField();
        tfCEP = new javax.swing.JFormattedTextField();
        tfTelefoneClientes = new javax.swing.JFormattedTextField();
        btExcluir = new javax.swing.JButton();

        setTitle("Clientes");

        tfClientes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfClientesActionPerformed(evt);
            }
        });

        botaoPesquisarCliente.setText("Pesquisar");
        botaoPesquisarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoPesquisarClienteActionPerformed(evt);
            }
        });

        tbClientes.setModel(tmClientes);
        tbClientes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmClientes = tbClientes.getSelectionModel();
        lsmClientes.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
                if(! e.getValueIsAdjusting()){
                    tbClientesLinhaSelecionada(tbClientes);
                }
            }
        });
        jScrollPane1.setViewportView(tbClientes);

        labelNome.setText("Nome: *");

        tfNomeClientes.setEditable(false);

        labelEndereco.setText("Endereço: ");

        tfEndereco.setEditable(false);

        labelBairro.setText("Bairro: ");

        tfBairro.setEditable(false);

        labelCidade.setText("Cidade: ");

        tfCidade.setEditable(false);

        labelUF.setText("UF: ");

        tfUF.setEditable(false);

        labelCEP.setText("CEP:");

        labelTelefoneClientes.setText("Telefone:");

        botaoNovoCliente.setText("Novo");
        botaoNovoCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoNovoClienteActionPerformed(evt);
            }
        });

        botaoSalvarCliente.setText("Salvar");
        botaoSalvarCliente.setEnabled(false);
        botaoSalvarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSalvarClienteActionPerformed(evt);
            }
        });

        botaoAlterarCliente.setText("Alterar");
        botaoAlterarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAlterarClienteActionPerformed(evt);
            }
        });

        botaoCancelarCliente.setText("Cancelar");
        botaoCancelarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarClienteActionPerformed(evt);
            }
        });

        botaoFecharCliente.setText("Fechar");
        botaoFecharCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoFecharClienteActionPerformed(evt);
            }
        });

        labelAviso.setText("*: Campos com preenchimento obrigatório");

        labelCPFCNPJ.setText("CPF: ");

        tfCPF.setEditable(false);
        try {
            tfCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        tfCEP.setEditable(false);
        try {
            tfCEP.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        tfTelefoneClientes.setEditable(false);
        try {
            tfTelefoneClientes.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelAviso)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(tfClientes)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(botaoPesquisarCliente))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 498, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(labelNome)
                                        .addGap(344, 344, 344)
                                        .addComponent(labelCPFCNPJ)))
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(labelCidade)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(tfCidade)
                                                .addGap(26, 26, 26)))
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(labelUF)
                                            .addComponent(tfUF, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(tfCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(labelCEP))
                                        .addGap(36, 36, 36))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(labelEndereco)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(tfEndereco)
                                        .addGap(18, 18, 18)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelBairro)
                                    .addComponent(tfBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(tfTelefoneClientes, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(labelTelefoneClientes)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(tfNomeClientes)
                                .addGap(18, 18, 18)
                                .addComponent(tfCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(botaoNovoCliente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(botaoSalvarCliente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoAlterarCliente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btExcluir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(botaoCancelarCliente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoFecharCliente)))
                        .addGap(26, 26, 26))))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botaoAlterarCliente, botaoCancelarCliente, botaoFecharCliente, botaoNovoCliente, botaoPesquisarCliente, botaoSalvarCliente, btExcluir});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoPesquisarCliente))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelNome)
                    .addComponent(labelCPFCNPJ))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfNomeClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelEndereco)
                    .addComponent(labelBairro))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelUF, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelCEP)
                    .addComponent(labelTelefoneClientes)
                    .addComponent(labelCidade))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tfTelefoneClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(tfUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(tfCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoNovoCliente)
                    .addComponent(botaoSalvarCliente)
                    .addComponent(botaoAlterarCliente)
                    .addComponent(botaoCancelarCliente)
                    .addComponent(botaoFecharCliente)
                    .addComponent(btExcluir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelAviso))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfClientesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfClientesActionPerformed

    private void botaoFecharClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoFecharClienteActionPerformed
       if(JOptionPane.showConfirmDialog(null, "Deseja sair da tela de Clientes?", "ATENÇÃO!", JOptionPane.YES_NO_OPTION)==0){
           this.hide();
       }
       desabilitarCampos();
       tbClientes.getSelectionModel().clearSelection();
    }//GEN-LAST:event_botaoFecharClienteActionPerformed

    private void botaoNovoClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovoClienteActionPerformed
       tipoCadastro = "novo";
       novoCliente();
    }//GEN-LAST:event_botaoNovoClienteActionPerformed

    private void botaoSalvarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSalvarClienteActionPerformed
      if(tipoCadastro.equals("novo")){
          try {
              cadastrarCliente();
          } catch (SQLException ex) {
              Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
          }
          try {
              listarClientes();
          } catch (SQLException ex) {
              Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
          }
      } else if(tipoCadastro.equals("alterar")){
          try {
              alterarCliente();
          } catch (SQLException ex) {
              Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
          }
          try {
              listarClientes();
          } catch (SQLException ex) {
              Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
          }
          desabilitarCampos();
      }
    }//GEN-LAST:event_botaoSalvarClienteActionPerformed

    private void botaoPesquisarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoPesquisarClienteActionPerformed
        try {
            listarClientes();
        } catch (SQLException ex) {
            Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_botaoPesquisarClienteActionPerformed

    private void botaoAlterarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAlterarClienteActionPerformed
        tipoCadastro = "alterar";
        alteraCliente();
    }//GEN-LAST:event_botaoAlterarClienteActionPerformed

    private void botaoCancelarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarClienteActionPerformed
        if(JOptionPane.showConfirmDialog(null, "Deseja Cancelar esta ação?", "ATENÇÃO", JOptionPane.YES_NO_OPTION)==0){
            desabilitarCampos();
        }
    }//GEN-LAST:event_botaoCancelarClienteActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        try {
            excluir();
        } catch (SQLException ex) {
            Logger.getLogger(Clientes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    
    public void habilitarCampos(){
        tfNomeClientes.setEditable(true);
        tfEndereco.setEditable(true);
        tfBairro.setEditable(true);
        tfCEP.setEditable(true);
        tfCPF.setEditable(true);
        tfTelefoneClientes.setEditable(true);
        tfCidade.setEditable(true);
        tfUF.setEditable(true);
        botaoSalvarCliente.setEnabled(true);
        botaoFecharCliente.setEnabled(false);  
        btExcluir.setEnabled(true);
        
    }
    public void desabilitarCampos(){
        tfNomeClientes.setEditable(false);
        tfEndereco.setEditable(false);
        tfBairro.setEditable(false);
        tfCEP.setEditable(false);
        tfCPF.setEditable(false);
        tfTelefoneClientes.setEditable(false);
        tfCidade.setEditable(false);
        tfUF.setEditable(false);
        botaoSalvarCliente.setEnabled(false);
        botaoAlterarCliente.setEnabled(true);
        botaoNovoCliente.setEnabled(true);
        botaoFecharCliente.setEnabled(true);
        btExcluir.setEnabled(true);
       
    }
    private void novoCliente(){
        btExcluir.setEnabled(false);
        botaoAlterarCliente.setEnabled(false);
        habilitarCampos();
        tfNomeClientes.setText("");
        tfEndereco.setText("");
        tfBairro.setText("");
        tfCEP.setText("");
        tfCPF.setText("");
        tfTelefoneClientes.setText("");
        tfCidade.setText("");
        tfUF.setText("");
    }
    public boolean verificarCampos(){
        if(!tfNomeClientes.getText().trim().equals("")){
            return true;
        }else{
            JOptionPane.showMessageDialog(this,"Campo nome é obrigatório");
            return false;
        }
        
    }

    public boolean verificarUF(){
        if(tfUF.getText().length() > 2){
            JOptionPane.showMessageDialog(null, "Campo UF deve possuir apenas 2 Letras!");
            return false;
        } else
             return true;        
    }
    
    public boolean verificaCPF(String cpf) throws SQLException{
        boolean resultado = false;
        ClienteDAO dao = new ClienteDAO();
        
        clientes = dao.listarClientes("%"+ tfClientes.getText().trim() + "%");
        
        if(clientes.isEmpty()){
            resultado = true;
        } else{
            JOptionPane.showMessageDialog(null, "Um cliente com esse mesmo CPF já foi cadastrado, insira outro CPF!");
            tfCPF.requestFocus();
            resultado = false;
        }
        
        return resultado;
        
    }
    private void cadastrarCliente() throws SQLException,MySQLIntegrityConstraintViolationException {
       if(verificarCampos()&& verificarUF()&&verificaCPF("%"+tfCPF.getText().trim() + "%")){
          
           Cliente cli = new Cliente();
           cli.setNome(tfNomeClientes.getText().trim()); 
           cli.setCPF(tfCPF.getText().trim());
           cli.setCidade(tfCidade.getText().trim());           
           cli.setEndereco(tfEndereco.getText().trim());
           cli.setBairro(tfBairro.getText().trim());
           cli.setCidade(tfCidade.getText().trim());
           cli.setUF(tfUF.getText().trim());
           cli.setCEP(tfCEP.getText().trim());
           cli.setTelefone(tfTelefoneClientes.getText().trim());
           ClienteDAO cliente = new ClienteDAO();
           cliente.cadastrarCliente(cli);
           JOptionPane.showMessageDialog(null, cli.getNome()+ " cadastrado com Sucesso!");
           mostrarClientes(clientes);
            
       }      
    }
    private void mostrarClientes(List<Cliente> clientes){
        while(tmClientes.getRowCount()>0){
            tmClientes.removeRow(0);
        }
        if(clientes.size() == 0){
            JOptionPane.showMessageDialog(null, "Nenhum cliente encontrado");
        } else{
            String[] linha = new String[]{null, null, null, null};
            for(int i = 0; i < clientes.size(); i++){
                tmClientes.addRow(linha);
                tmClientes.setValueAt(clientes.get(i).getCodigo(), i, 0);
                tmClientes.setValueAt(clientes.get(i).getNome(), i, 1);
                tmClientes.setValueAt(clientes.get(i).getCPF(), i, 2);
                tmClientes.setValueAt(clientes.get(i).getTelefone(), i, 3);
               // tmClientes.setValueAt(clientes.get(i).getCPF(), i, 4);
            }
        }
    }
    private void listarClientes() throws SQLException{
        ClienteDAO cli = new ClienteDAO();
        clientes = cli.listarClientes("%"+ tfClientes.getText().trim() + "%");
        mostrarClientes(clientes);
    }    
    private void tbClientesLinhaSelecionada(JTable table){
        if(tbClientes.getSelectedRow() != -1){ //retorna -1 quando não há nenhuma linha da tabela selecionada
            tfNomeClientes.setText(clientes.get(table.getSelectedRow()).getNome());
            tfCPF.setText(clientes.get(table.getSelectedRow()).getCPF());
            tfEndereco.setText(clientes.get(table.getSelectedRow()).getEndereco());
            tfBairro.setText(clientes.get(table.getSelectedRow()).getBairro());
            tfCidade.setText(clientes.get(table.getSelectedRow()).getCidade());
            tfUF.setText(clientes.get(table.getSelectedRow()).getUF());
            tfCEP.setText(clientes.get(table.getSelectedRow()).getCEP());
            tfTelefoneClientes.setText(clientes.get(table.getSelectedRow()).getTelefone());
        } else{
            novoCliente();
        }
}
    private void alteraCliente(){
        if(tbClientes.getSelectedRow()!= -1){
            btExcluir.setEnabled(false);
            botaoNovoCliente.setEnabled(false);
            habilitarCampos();
        } else{
            JOptionPane.showMessageDialog(this, "Selecione um cliente!");
        }
    }
    private void alterarCliente() throws SQLException{
         if(verificarCampos()&& verificarUF()){
           Cliente cli = new Cliente();
           cli.setNome(tfNomeClientes.getText().trim()); 
           cli.setCidade(tfCidade.getText().trim());           
           cli.setEndereco(tfEndereco.getText().trim());
           cli.setBairro(tfBairro.getText().trim());
           cli.setCidade(tfCidade.getText().trim());
           cli.setUF(tfUF.getText().trim());
           cli.setCEP(tfCEP.getText().trim());
           cli.setTelefone(tfTelefoneClientes.getText().trim());
           cli.setCodigo(clientes.get(tbClientes.getSelectedRow()).getCodigo());
            ClienteDAO cliente = new ClienteDAO();
           cliente.alterarCliente(cli);
           JOptionPane.showMessageDialog(null, cli.getNome()+ " alterado com Sucesso!");
           desabilitarCampos(); 
               
       } 
    }
    
    public void excluir() throws SQLException{
        if(JOptionPane.showConfirmDialog(null, "Deseja excluir este cliente?", "ATENÇÃO", JOptionPane.YES_NO_OPTION)==0){
            ClienteDAO cli = new ClienteDAO();
            cli.excluirCliente(clientes.get(tbClientes.getSelectedRow()));
            JOptionPane.showMessageDialog(null, "Cliente excluido com sucesso!");
            listarClientes();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Clientes().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAlterarCliente;
    private javax.swing.JButton botaoCancelarCliente;
    private javax.swing.JButton botaoFecharCliente;
    private javax.swing.JButton botaoNovoCliente;
    private javax.swing.JButton botaoPesquisarCliente;
    private javax.swing.JButton botaoSalvarCliente;
    private javax.swing.JButton btExcluir;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelAviso;
    private javax.swing.JLabel labelBairro;
    private javax.swing.JLabel labelCEP;
    private javax.swing.JLabel labelCPFCNPJ;
    private javax.swing.JLabel labelCidade;
    private javax.swing.JLabel labelEndereco;
    private javax.swing.JLabel labelNome;
    private javax.swing.JLabel labelTelefoneClientes;
    private javax.swing.JLabel labelUF;
    private javax.swing.JTable tbClientes;
    private javax.swing.JTextField tfBairro;
    private javax.swing.JFormattedTextField tfCEP;
    private javax.swing.JFormattedTextField tfCPF;
    private javax.swing.JTextField tfCidade;
    private javax.swing.JTextField tfClientes;
    private javax.swing.JTextField tfEndereco;
    private javax.swing.JTextField tfNomeClientes;
    private javax.swing.JFormattedTextField tfTelefoneClientes;
    private javax.swing.JTextField tfUF;
    // End of variables declaration//GEN-END:variables
}
